#include <string.h>
#include <stdio.h>
#include <dirent.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "freertos/queue.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event_loop.h"
#include "esp_log.h"
#include "nvs_flash.h"

#include "lwip/err.h"
#include "lwip/sockets.h"
#include "lwip/sys.h"
#include "lwip/netdb.h"
#include "lwip/dns.h"
#include "apps/tftp/tftp_server.h"
#include "user_event.h"
#include "tftp_disk.h"

static const char *TAG = "tfpt_disk";

void* disk_tftp_open(const char* fname, const char* mode, u8_t write) {
    
    if(write) {
        ESP_LOGI(TAG, "file write...%s", fname);
        return fopen(fname, "w");
    } else {
        ESP_LOGI(TAG, "file read...%s", fname);
        return fopen(fname, "r");
    }
}

void disk_tftp_close(void* handle) {
    if(handle == NULL) {
        return;
    }
    fclose(handle);
    handle = NULL;
}

int disk_tftp_read(void* handle, void* buf, int bytes) {
    if(handle == NULL) {
        return -1;
    }
    return fread(buf, 1, bytes, handle);
}

int disk_tftp_write(void* handle, struct pbuf* p) {
    if(handle == NULL) {
        return -1;
    }
    fwrite(p->payload, 1, p->len, handle);
    return 0;
}

const struct tftp_context ctx = {
    .open = &disk_tftp_open,
    .close = &disk_tftp_close,
    .read = &disk_tftp_read,
    .write = &disk_tftp_write,
};

portBASE_TYPE tftp_disk_init(void)
{
    return tftp_init(&ctx);
}
